//
//  mttViewController.m
//  mtt
//
//  Created by Gerfried Mikusch on 16.04.2010.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "mttViewController.h"
#import "OptionViewController.h"
#import "mttImage.h"
#import "mttBackgroundImage.h"
#import "mttPoint.h"
#import "mttImageGroup.h"

@implementation mttViewController

@synthesize images, imageGroups;

NSMutableDictionary *pinnedImages;
NSNumber *imagekey;
NSNumber *imageGroupKey;
int pinID = 0;
mttBackgroundImage *bgImage;
OptionViewController *optionView;

#pragma mark -
#pragma mark loading/unload the View

- (void)viewDidLoad {
    [super viewDidLoad];
	
	
	//Load Option View
	optionView = [[OptionViewController alloc] initWithNibName:@"OptionViewController" bundle:[NSBundle mainBundle]];
	optionView.delegate = self;
	//optionView = optionViewCont.view;
	
	
	//Size & Position of OptionView
	CGFloat optionViewFrameWidth = optionView.view.frame.size.width;						//Width = 80
	CGFloat superViewFrameWidth = self.view.frame.size.width;								//Width = 768 -> sollte eigentlich 1024 sein da Querformat
	CGFloat newXOrigin = superViewFrameWidth - optionViewFrameWidth;
	
	CGFloat optionViewFrameHeight = optionView.view.frame.size.height;						//Height = 130
	CGFloat superViewFrameHeight = self.view.frame.size.height;								//Height = 1024 -> sollte eigentlich 768 sein da Querformat
	CGFloat newYOrigin = superViewFrameHeight - optionViewFrameHeight;
	
	CGRect rect = optionView.view.frame;
	rect.origin = CGPointMake(newXOrigin+optionViewFrameWidth, newYOrigin);					//X = 690; Y = 899
	//rect.size = CGSizeMake(optionView.view.frame.size.width, optionView.view.frame.size.height);		
	optionView.view.frame = rect;
	
	
	//Hier Animationsanfang!?
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:context];
	
	[UIView setAnimationDuration:1.0];
	
	optionView.view.transform = CGAffineTransformMakeTranslation(-optionViewFrameWidth, 0);			//Warum 300????
	
	
	[self.view addSubview:optionView.view];		//Add LibraryView as Subview
	[UIView commitAnimations];
	//Hier Animationsende!?
	
	//dict für die hinzugefuegten images, imageGroups, und pinned images
	images = [[NSMutableDictionary alloc] init];
	imageGroups = [[NSMutableDictionary alloc] init];
	pinnedImages = [[NSMutableDictionary alloc] init];
	imagekey = [NSNumber numberWithInt:0];
	imageGroupKey = [NSNumber numberWithInt:0];
	
}

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}



#pragma mark -
#pragma mark Set images

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	
	//mttImage erstellen und mit dem Bild aus imagePicker initialisieren
	mttImage *mttImg = [[mttImage alloc] initWithImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
	
	
	mttImg.delegate = self;
	
	//Die Bilder werden "fast" im Zentrum eingefügt.
	mttImg.center = self.view.center;
	
	//Sind die Bilder größer als das Display, sollen sie verkleinert werden
	if (mttImg.frame.size.width > self.view.frame.size.width || mttImg.frame.size.height > self.view.frame.size.height) {
		NSLog(@"inIF");
		mttImg.contentMode = UIViewContentModeScaleAspectFill;
		
		CGRect rect = self.view.frame;
		rect.size = CGSizeMake(1024, 768);
		mttImg.frame = rect;
	}
	
	
	[self.view addSubview:mttImg];
	[self.view bringSubviewToFront:optionView.view];
	
	NSLog(@"geht noch");
	[images setObject:mttImg forKey:imagekey];
	mttImg.imagekey = imagekey;
	
	//Bild zur verknüpfungsliste hinzufügen mit leerem mutable Array
	NSMutableArray *pinnedToActualImage = [[NSMutableArray alloc] init];
	[pinnedImages setObject:pinnedToActualImage forKey:imagekey];
	
	int newKey = [imagekey intValue] +1;
	imagekey = [NSNumber numberWithInt:newKey];
	
	
	NSLog(@"imagekey:");
	for (id key in images) {
		
        NSLog(@"key: %@, value: %@", key, [images objectForKey:key]);
		
    }
	
	
	//Wenn gerade ein Hintergrundbild bearbeitet wird -> bearbeiten ausschalten!
	if (bgImage != nil && bgImage.panRecognizer.enabled == YES) {
		[bgImage setGestureRecognizersEnabled:NO];				//GestureRecognizer beim Hintergrund disablen
		[self setImagesAlpha:1.0];								//Keine Transparenz der Bilder
		[self setImagesInteraction:YES];						//Interaction der Bilder einschalten
	}
	
	
	[mttImg release]; //Ist das hier richtig?????
	[pinnedToActualImage release];
}

#pragma mark -
#pragma mark image searching



-(NSMutableArray *)getImagesAtPoint:(CGPoint)point {
	
	// TODO: Nicht im Transparenten Bereich pinnen
	
	NSMutableArray *imagesAtPoint = [[NSMutableArray alloc] init];
	
	//Durchlaufe alle Bilder und überprüfe ob sie an diesem Punkt liegen
	for (int i=0; i<=images.count; i++) {
		NSNumber *num = [NSNumber numberWithInt:i];
		mttImage *img = (mttImage *)[images objectForKey:num];
		CGPoint pointForView = [img convertPoint:point fromView:nil];
		//NSLog(@"pointForView: %i x: %f, y: %f", img.imagekey, pointForView.x, pointForView.y);
		
		//Liegt ein bild an dem Punkt füge die id des bilds als NSNumber hinzu
		if ([img pointInside:pointForView withEvent:nil]) {
			[imagesAtPoint addObject:img.imagekey];
		}
		
	}
	
	return imagesAtPoint;
	
}

-(BOOL)isImageAttached:(NSNumber *)attachedID atImage:(NSNumber *)imageID {
	
	//Hängt das bild mit attachedID schon beim bild mit ImageID dabei?
		
		BOOL isAttached = NO;
		
	//das passt nicht, weil hier nur die angehängten bilder genommen werden, aber nicht das bild bei dems dabeihängt selbst ??
		NSMutableArray *imagesAtImage = [pinnedImages objectForKey:imageID];
		
		for (int i=0; i<imagesAtImage.count; i++) {
			if([[imagesAtImage objectAtIndex:i] isEqualToNumber:attachedID]) isAttached = YES;
			NSLog(@"bla");
		
		}
		//if ([attachedID intValue] == [imageID intValue]) {
	if( [attachedID isEqualToNumber:imageID]) {
			isAttached = YES;}
		 
		return isAttached;
	

}

-(BOOL)isID:(NSNumber *)myID inArray:(NSMutableArray *)array {
	
	BOOL retVal = NO;
	
	for (int i=0; i<array.count; i++) {
		if ([[array objectAtIndex:i] isEqualToNumber:myID]) {
			retVal = YES;
		}
	}
	
	return retVal;
	
}

-(void)addNextImage:(NSMutableArray *)next toActualImage:(NSMutableArray *)actual {
	
	for (int i=0; i<next.count; i++) {
		for (int j=0; j<actual.count; j++) {
			
			if (![self isImageAttached:[next objectAtIndex:i] atImage:[actual objectAtIndex:j]]) {
				//[actual addObject:[next objectAtIndex:i]];
				[[pinnedImages objectForKey:[actual objectAtIndex:j]] addObject:[next objectAtIndex:i]];
			}
			
		}
	}
	
}




#pragma mark -
#pragma mark Image & Image Group Delegate Methods


-(void)performPinOnImages:(CGPoint)pinPoint withCallerId:(NSNumber*)callerId {
	
	NSLog(@"pinPoint x: %f, pinPoint y: %f", pinPoint.x, pinPoint.y);
	
	/*Id für den Pin und mttPoint Objekt mit id und Location
	 !!!: Location des mttPoint ist in device-Koordinaten*/
	pinID = pinID + 1;
	mttPoint *pin = [[mttPoint alloc] initWithID:pinID andLocation:pinPoint];
	
	//Bilder die diesen PinPoint erhalten sollen
	NSMutableArray *imagesToPin = [self getImagesAtPoint:pinPoint];
	
	NSLog(@"imagesToPin ....... %i", imagesToPin.count);
	//Nur wenn überhaupt ein bild darunter liegt soll  allen Bildern ein pinPoint zugewiesen werden
	if (imagesToPin.count>1) {
		
		
		for (int i = 0; i<imagesToPin.count-1; i++) {
			
			mttImage *actualImage = (mttImage *)[images objectForKey:[imagesToPin objectAtIndex:i]];
			mttImage *nextImage = (mttImage *)[images objectForKey:[imagesToPin objectAtIndex:i+1]];
			
			NSMutableArray *attachedToActual = [pinnedImages objectForKey:actualImage.imagekey];
			NSMutableArray *attachedToNext = [pinnedImages objectForKey:nextImage.imagekey];
			
			if (i == 0 && ![self isID:actualImage.imagekey inArray:attachedToActual]) {
				//if (attachedToActual.count <= 1){
				[attachedToActual addObject:actualImage.imagekey];
				//}
			}
			//[attachedToActual addObject:actualImage.imagekey];
			if (![self isID:nextImage.imagekey inArray:attachedToNext]) {
				[attachedToNext addObject:nextImage.imagekey];
			}
			//NSLog("keineahnung %a", attachedToActual);
			
			[self addNextImage:attachedToNext toActualImage:attachedToActual];
			[self addNextImage:attachedToActual toActualImage:attachedToNext];
			
			[actualImage setPin:pin];
			
		}
	
	
		/* TODO:	ImageGroup erzeugen
					Alle zusammenhängenden Bildern sollen in eine mttImageGroup die als Subview dem mainController hinzugefügt werden.
					Die Bilder werden wiederum der ImageGroup als Subview hinzugefügt und selbst aus dem mainController subviews gelöscht.
		*/
	
		mttImageGroup* imageGroup = [[mttImageGroup alloc] init];
		//imageGroup.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		//[imageGroup sizeToFit];
		imageGroup.frame=CGRectMake(0, 0, 1024, 768);
		imageGroup.delegate = self;
		imageGroup.imageGroupKey = imageGroupKey;
		imageGroup.backgroundColor = [UIColor colorWithRed:2 green:2 blue:2 alpha:2];

	
		NSMutableArray* keysForGroup = [pinnedImages objectForKey:callerId];
	
	
	
		for(int i = 0;i<keysForGroup.count;i++){
	
			mttImage* actualImage = [images objectForKey:[keysForGroup objectAtIndex:i]];
			//NSLog(@"image width %f, image height%f", actualImage.frame.size.width, actualImage.frame.size.height);
			//imageGroup.frame = actualImage.frame;
			[imageGroup addSubview:actualImage];
		
		
		}
	
		NSLog(@"imagegroup subview counts %@",[imageGroup subviews]);
		[imageGroups setObject:imageGroup forKey:imageGroup.imageGroupKey];
	
		int newKey = [imageGroupKey intValue] +1;
		imageGroupKey = [NSNumber numberWithInt:newKey];
	
		[imageGroup sizeToFit];
	
		//NSLog(@"NEWS SIZE width: %f height: %f", size.width, size.height);
	
		[self.view addSubview:imageGroup];
		//[super.view addSubview:imageGroup];
		//[self.view bringSubviewToFront:imageGroup];
	
	
	}
	
	for (id key in pinnedImages) {
		NSLog(@"---------------------    Pinned Images ---------------------------");
        NSLog(@"key: %@, value: %@", key, [pinnedImages objectForKey:key]);
		
    }

}



-(void)setMttBackground:(mttImage *) selectedImage {
	/*
	if (bgImage != nil) {
		[bgImage removeFromSuperview];
	}
	
	bgImage = nil;
	
	
	//Background image erzeugen
	bgImage = [[mttBackgroundImage alloc] initWithImage:selectedImage.image];
	bgImage.delegate = self;
	
	//Aus dem Dictionary entfernen
	[images removeObjectForKey:selectedImage.imagekey];
	
	//mttBackgroundImage als subview hinzufügen
	[self.view insertSubview:bgImage atIndex:0];
	
	//isBgSet = YES;
	
	
*/
}	
	

-(void)setImagesAlpha:(CGFloat) alpha {
	for (id key in images) {
		//Hier Animationsanfang!?
		CGContextRef context = UIGraphicsGetCurrentContext();
		[UIView beginAnimations:nil context:context];
		
		[UIView setAnimationDuration:1.0];
		
		[[images objectForKey:key] setAlpha:alpha];
		
		[UIView commitAnimations];
		
	}
}

-(void)setImagesInteraction:(BOOL) interaction {
	for (id key in images) {
		
		[[images objectForKey:key] setGestureRecognizersEnabled:interaction];
		
	}
}

-(void)bringViewToFront:(UIView *) subView {
	[self.view bringSubviewToFront:subView];
}

-(void)bringOptionViewToFront {
	[self.view bringSubviewToFront:optionView.view];
}

-(void)sendViewToBack:(UIView *) subView {
	[self.view sendSubviewToBack:subView];
}

-(void)removeImage:(NSNumber *) imageKey {
	[images removeObjectForKey:imageKey];
}


#pragma mark -
#pragma mark optionView Delegate Methods

-(void)presentHelpView:(UINavigationController *) navController {
	[self presentModalViewController:navController animated:YES];
}

#pragma mark -
#pragma mark HelpViewController Delegate Methods

-(void)didDismissHelpView {
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark init & dealloc

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

- (void)dealloc {
	
	optionView = NULL;
	[super dealloc];
	
}


@end
